package mspdt.ubzuuch.mn;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Resources.NotFoundException;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ExpandableListView.OnChildClickListener;

public class RentActivity extends Activity{
       JSONfuncObject js=new JSONfuncObject();
       String rent[]={"Орон сууц","Барилга","Хашаа Байшин","Зуслан"};
       String child_data[][]={{"1 өрөө","2 өрөө","3 өрөө","4+ өрөө","Түрээслэгдсэн"},
    		   {"Амины орон сууц","Обьект","Үйлчилгээний байр","Газар","Түрээслэгдсэн"},
    		   {"15 сая төгрөг хүртэл","15-30 сая төгрөг хүртэл","30 сая хүртэл","Үйлчилгээтэй хашаа байшин","Түрээслэгдсэн"},
    		   {"30 сая хүртэл","30-60 сая хүртэл","60 саяас дээш","Зуслангын газар","Түрээслэгдсэн"}};
       private ExpandableListView expList_trade;
        private ArrayList<String> parent_datas = new ArrayList<String>();
          private ArrayList<Integer> parent_counts = new ArrayList<Integer>();
          private ArrayList<ArrayList<String>> child_datas = new ArrayList<ArrayList<String>>();
          private ArrayList<ArrayList<Integer>> child_counts = new ArrayList<ArrayList<Integer>>();
          private MainExpandableAdapter main_adapter;
          private String url = "";
          private NetworkConnectionClass network;
      	@Override
    	public void onBackPressed() {
    	   finish();
    	   overridePendingTransition(R.anim.no_anim, R.anim.no_anim);
    	}
        @Override
        public void onCreate(Bundle savedInstanceState)
        {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_rent);
                network=new NetworkConnectionClass(this);
                expList_trade = (ExpandableListView)findViewById(R.id.exp_list_rent);
                expList_trade.setGroupIndicator(null);
                expList_trade.setOnChildClickListener(new OnChildClickListener() {
                       
                        @Override
                        public boolean onChildClick(ExpandableListView parent, View v,
                                        int groupPosition, int childPosition, long id) {
                                // TODO Auto-generated method stub
                                //Child дээр дарахад тухайн child-н ID гаар нь дараагын дэлгэрэнгүйг харах
                        	if(child_counts.get(groupPosition).get(childPosition)>0)
            				{
                        		Intent intent = new Intent(RentActivity.this, ItemActivity.class);
                                if(childPosition!=4)
                                {
                                	if(childPosition==3 && groupPosition==0)
                					{
                						String child = "4 өрөө";
                						url = "http://202.131.237.185/ubzuuch/web/banner/getbair?roomnum="+child+
                								"&category=2"+"&page=1";
                					}
                                	else
                                		url = "http://202.131.237.185/ubzuuch/web/banner/getbair?roomnum="+child_datas.get(groupPosition).get(childPosition)+
                						"&category=2"+"&page=1";
                                }
                					
                				else
                					url = "http://202.131.237.185/ubzuuch/web/banner/getbair?roomnum="+"харах"+
                					"&category=2"+"&page=1"+"&type="+(groupPosition+1);;
                                Bundle bundle = new Bundle();
                                bundle.putString("URL", url);
                                bundle.putInt("title", R.id.title_menu_2);
                                intent.putExtras(bundle);
                                startActivity(intent);
                                overridePendingTransition(R.anim.right_in, R.anim.no_anim);
            				}
                        	else
                        		Toast.makeText(RentActivity.this, "Мэдээ хоосон байна", 2000).show();
                                
                                return false;
                        }
                });
                createTitleComponents();
                findViewById(R.id.title_menu_2).setBackgroundResource(R.drawable.text_background);
                focusOnView();
                createExpData();
        }
        public void onResume()
        {
                super.onResume();
                focusOnView();
        }
        private final void focusOnView(){
        new Handler().post(new Runnable() {
            @Override
            public void run() {
                findViewById(R.id.title_scroll_view).scrollTo(findViewById(R.id.title_menu_2).getLeft()-10, 0);
            }
        });
    }
        public void createExpData()
        {
                //JSON уншаагүй байгаа болохоор тест маягаар гараас шууд өгөгдөл уншиж байгаа Json уншихад Thread доторхыг солино
                parent_counts.clear();
                parent_datas.clear();
                child_datas.clear();
                child_counts.clear();
               
                final ProgressDialog dialog = ProgressDialog.show(RentActivity.this, null,
                        getResources().getString(R.string.dialog_please_wait), true);
       
                        final Handler handler = new Handler() {
                           public void handleMessage(Message msg) {
                                   //RUN доторх үйлдэл хийгдэж дуусахад уншсан мэдээллүүдээ adapter-т хийж өгнө
                        	   if(msg.what==1)
                        	   {
                        		   main_adapter = new MainExpandableAdapter(RentActivity.this, parent_datas, parent_counts, child_datas, child_counts);
                                   expList_trade.setAdapter(main_adapter);
                        	   }
                        	   else
                        		   Toast.makeText(RentActivity.this, "Сервэртэй холбогдоход алдаа гарлаа", 3000).show();
                        	   dialog.dismiss(); 
                              }
                           };
                        Thread checkUpdate = new Thread() {  
                           public void run() {
                        	   if(network.isConnectedToServer(getResources().getString(R.string.json_main_data_counts)+2, 5000) && network.isNetworkConnected())
                        	   {
                        		   JSONObject jobj=js.getJSONfromURL(getResources().getString(R.string.json_main_data_counts)+2); 
                            	   try {
    								JSONArray ja_apa = jobj.getJSONArray(getResources().getString(R.string.json_main_get_apartment_counts));
    								 JSONArray ja_bar=jobj.getJSONArray(getResources().getString(R.string.json_main_get_barilga_counts));
    									JSONArray ja_kha=jobj.getJSONArray(getResources().getString(R.string.json_main_get_khashaa_counts));
    									JSONArray ja_zus=jobj.getJSONArray(getResources().getString(R.string.json_main_get_zuslan_counts));
    									JSONArray ja_tvr=jobj.getJSONArray(getResources().getString(R.string.json_main_get_zarsan_counts));
    									   //энэ дотор Json-с дата уншиж харгалзах утгуудад нь хийж өгнө
    									        for(int i=0;i<rent.length;i++)
    	                                        {
    	                                                parent_datas.add(rent[i]);
    	                                                ArrayList<String> child_data = new ArrayList<String>();
    	                                                for(int j=0;j<RentActivity.this.child_data[i].length;j++)
    	                                                {
    	                                                        child_data.add(RentActivity.this.child_data[i][j]);                                                      
    	                                                }   
    	                                                child_datas.add(child_data);
    	                                        }	
    									        ArrayList<Integer> child_tvrees = new ArrayList<Integer>();
                                                ArrayList<Integer> child_barilga = new ArrayList<Integer>();
                                                ArrayList<Integer> child_khashaa = new ArrayList<Integer>();
                                                ArrayList<Integer> child_zuslan = new ArrayList<Integer>();
            									for(int a=0;a<ja_apa.length();a++){	            										
            										child_tvrees.add(ja_apa.getInt(a));  
            									
            										}
            									child_tvrees.add(ja_tvr.getInt(0));
            									child_counts.add(child_tvrees);
            									
            									for(int a=0;a<ja_bar.length();a++){
            										
            										child_barilga.add(ja_bar.getInt(a));
            										}
            									child_barilga.add(ja_tvr.getInt(1));
            									child_counts.add(child_barilga);
            									
            									for(int a=0;a<ja_kha.length();a++){
            										
            										child_khashaa.add(ja_kha.getInt(a));
            										}
            									child_khashaa.add(ja_tvr.getInt(2));
            									child_counts.add(child_khashaa);
            									for(int a=0;a<ja_zus.length();a++){
            	
            										child_zuslan.add(ja_zus.getInt(a));
            										}
            									child_zuslan.add(ja_tvr.getInt(3));
            									child_counts.add(child_zuslan);
    							}
    							catch (NotFoundException e1) {
    								// TODO Auto-generated catch block
    								e1.printStackTrace();
    							} catch (JSONException e1) {
    								// TODO Auto-generated catch block
    								e1.printStackTrace();
    							}
    								
                                    
                                       
                                       try {
    									JSONArray parent_counts=jobj.getJSONArray(getResources().getString(R.string.json_main_get_parent_counts));
    									
    									for(int l=0;l<parent_counts.length();l++){
    									RentActivity.this.parent_counts.add(parent_counts.getInt(l));
    									}
    									
    								} catch (NotFoundException e) {
    									// TODO Auto-generated catch block
    									e.printStackTrace();
    								} catch (JSONException e) {
    									// TODO Auto-generated catch block
    									e.printStackTrace();
    								}  
                                       
                                       handler.sendEmptyMessage(1);
                        	   }
                        	   else
                        		   handler.sendEmptyMessage(0);
                        	   
                              }
                           };
                        checkUpdate.start();
                    
                    	   
                       }
               
        
        public void createTitleComponents()
        {
                //Хуудасны дээр байрлах толгой хэсгийн хийх үйлдлүүд
               
                //Үндсэн товчлууруудын үйлдэл
                //Буцах товчлуур
                findViewById(R.id.back).setOnClickListener(new OnClickListener() {
                       
                        @Override
                        public void onClick(View v) {
                                // TODO Auto-generated method stub
                                finish();
                                overridePendingTransition(R.anim.no_anim, R.anim.no_anim);
                        }
                });
                //Хадгалсан мэдээ унших товчлуур
                findViewById(R.id.title_history).setOnClickListener(new OnClickListener() {
                       
                        @Override
                        public void onClick(View v) {
                                // TODO Auto-generated method stub
                        	startActivity(new Intent(RentActivity.this, ItemActivityFromDB.class));
                        	overridePendingTransition(R.anim.top_in, R.anim.no_anim);
                        }
                });
                //Хайх товчлуур
                findViewById(R.id.title_search).setOnClickListener(new OnClickListener() {
                       
                        @Override
                        public void onClick(View v) {
                                // TODO Auto-generated method stub
                        	startActivity(new Intent(RentActivity.this, SearchActivity.class));
                        	overridePendingTransition(R.anim.top_in, R.anim.no_anim);
                        }
                });
                //Тухай товчлуур
                findViewById(R.id.title_info).setOnClickListener(new OnClickListener() {
                       
                        @Override
                        public void onClick(View v) {
                                // TODO Auto-generated method stub
                        	startActivity(new Intent(RentActivity.this, InformationActivity.class));
                        	overridePendingTransition(R.anim.top_in, R.anim.no_anim);
                        }
                });
                //Home буюу лого дээр дарах үйлдэл
                findViewById(R.id.home).setOnClickListener(new OnClickListener() {
                       
                        @Override
                        public void onClick(View v) {
                                // TODO Auto-generated method stub
                        }
                });
               
               
               
                //Програмын үндсэн менюны үйлдлүүд
                findViewById(R.id.title_menu_1).setOnClickListener(new OnClickListener() {
                       
                        @Override
                        public void onClick(View v) {
                                // TODO Auto-generated method stub
                                //onClickMenu((TextView)v);
                                Intent intent = new Intent(RentActivity.this, MainActivity.class);
                                intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
                                startActivity(intent);
                                overridePendingTransition(R.anim.no_anim, R.anim.no_anim);
                        }
                });
                findViewById(R.id.title_menu_2).setOnClickListener(new OnClickListener() {
                       
                        @Override
                        public void onClick(View v) {
                                // TODO Auto-generated method stub
                                //Intent intent = new Intent(RentActivity.this, MainActivity.class);
                                //intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
                                //startActivity(intent);
                        }
                });
                findViewById(R.id.title_menu_3).setOnClickListener(new OnClickListener() {
                       
                        @Override
                        public void onClick(View v) {
                                // TODO Auto-generated method stub
                                Intent intent = new Intent(RentActivity.this, NewApartmentActivity.class);
                                intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
                                startActivity(intent);
                                overridePendingTransition(R.anim.no_anim, R.anim.no_anim);
                        }
                });
                findViewById(R.id.title_menu_4).setOnClickListener(new OnClickListener() {
                       
                        @Override
                        public void onClick(View v) {
                                // TODO Auto-generated method stub
                                Intent intent = new Intent(RentActivity.this, UBActivity.class);
                                intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
                                startActivity(intent);
                                overridePendingTransition(R.anim.no_anim, R.anim.no_anim);
                        }
                });
                findViewById(R.id.title_menu_5).setOnClickListener(new OnClickListener() {
                       
                        @Override
                        public void onClick(View v) {
                                // TODO Auto-generated method stub
                                Intent intent = new Intent(RentActivity.this, AutomobileActivity.class);
                                intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
                                startActivity(intent);
                                overridePendingTransition(R.anim.no_anim, R.anim.no_anim);
                        }
                });
        }
}